import { watch, ref, shallowRef, reactive, computed, getCurrentInstance, inject, toRefs } from "vue";
import { resetFormData, transFormData } from "@gd-accbuild-ui/gd-ui/utils";
import { getCurEventDynmicMetaAttrSettings } from "@gd-accbuild-core/hooks/useGetCurUiTemplateInfo";
import { globalConfig } from "@gd-accbuild-core/config";
import { isSuccessReqBackend, getBackendData, getBackendDataItems } from "@gd-accbuild-core/config/utils";
import gdLoadingService from "@/uni_modules/gd-accbuild-core/components/gd-accbuild-ui/gd-ui/gd-service/gd-loading-service/gd-loading-service";

const callback = (err) => {
  throw err;
};
const excludeLoadingStrategys = [
  "buildInRowDeleteBtn",
  "buildInContainerCancelBtn",
  "buildInAddBtn",
  "buildInAddChildIntoCurBtn",
];
const doEventstrategy = async ({
  newOperationEventParams,
  oldOperationEventParams,
  nodeKey,
  parentNodeKey,
  isShowContainer,
  containerEventFromConfig,
  metaItemList,
  props,
  formData,
  crudServiceVmTemplateConfig,
  treeRef,
}) => {
  console.log(oldOperationEventParams,'老参数')
  const eventstrategyName = newOperationEventParams.metaKey;
  const submitEventstrategyName = oldOperationEventParams?.metaKey;
  const containerStyle = newOperationEventParams?.containerAttr?.containerStyle;
  const vmCode = newOperationEventParams.metaItem.vmCode;
  const submitVmCode = oldOperationEventParams?.metaItem?.vmCode;
  const keyField = nodeKey.value;
  const parentKeyField = parentNodeKey.value;
  const curFormData = newOperationEventParams.formData;
  //设置容器显示隐藏
  let willIsShowContainer = isShowContainer.value;
  if (["buildInContainerCancelBtn", "buildInContainerSubmitBtn"].includes(eventstrategyName)) {
    willIsShowContainer = false;
    ///////
    containerEventFromConfig.formData = null;
  } else if (containerStyle && typeof containerStyle === "string") {
    willIsShowContainer = true;
    ///////
    containerEventFromConfig.formData = curFormData;
  }

  //点击事件前拦截
  let beforeClickFunc = (configObj) => {};
  if (newOperationEventParams.metaItem.hasOwnProperty("beforeClickFunc")) {
    if (typeof newOperationEventParams.metaItem["beforeClickFunc"] === "string") {
      beforeClickFunc = new Function("configObj", newOperationEventParams.metaItem.beforeClickFunc);
    } else if (typeof newOperationEventParams.metaItem["beforeClickFunc"] === "function") {
      beforeClickFunc = newOperationEventParams.metaItem.beforeClickFunc;
    }
  }

  const overrideEventFuncParams = {
    allBtnsEmitFormItemMetaConfig: props.allBtnsEmitFormItemMetaConfig,
    getCurEventDynmicMetaAttrSettings,
    resetFormData,
    transFormData,
    newOperationEventParams,
    isPassThrough: false,
    //////
    willIsShowContainer,
    eventstrategyName,
    keyField,
    parentKeyField,
    crudServiceVmTemplateConfig,
    submitVmCode,
    vmCode,
    formData: formData.value,
    formDataProxy: formData,
    metaItemList: metaItemList.value,
    metaItemListProxy: metaItemList,
    treeRef: treeRef.value,
  };

  const events = {
    //header
    buildInAddBtn: async () => {
      metaItemList.value = props.allBtnsEmitFormItemMetaConfig.buildInAddOrEditBtn.map((el) =>
        getCurEventDynmicMetaAttrSettings(el, "buildInAddBtn")
      );
      resetFormData(formData.value, metaItemList.value);
    },
    buildInAddChildIntoCurBtn: async () => {
      metaItemList.value = props.allBtnsEmitFormItemMetaConfig.buildInAddOrEditBtn.map((el) =>
        getCurEventDynmicMetaAttrSettings(el, "buildInAddBtn")
      );
      resetFormData(formData.value, metaItemList.value);
      formData.value[parentKeyField] = newOperationEventParams.formData[keyField];
      console.log(newOperationEventParams,'打印添加子')
    },
    buildInEditBtn: async () => {
      console.log("编辑树触发", props.allBtnsEmitFormItemMetaConfig,newOperationEventParams);
      metaItemList.value = props.allBtnsEmitFormItemMetaConfig.buildInAddOrEditBtn.map((el) =>
        getCurEventDynmicMetaAttrSettings(el, eventstrategyName.replace("Tree", ""))
      );
      const curRowKeyFieldVal = newOperationEventParams.formData[keyField];
      const params = { [keyField]: curRowKeyFieldVal };
      const res = await globalConfig.get({
        moduleCode: crudServiceVmTemplateConfig.tree.moduleCode,
        vmCode,
        params,
        vmTemplateConfig: crudServiceVmTemplateConfig.tree,
      });
      if (isSuccessReqBackend(res)) {
        formData.value = getBackendData(res);
      }
    },
    buildInRowDeleteBtn: async () => {},
    //容器内置按钮
    buildInContainerCancelBtn: async () => {},
    buildInContainerSubmitBtn: async () => {
      const submitEventStrategy = {
        buildInAddBtn: async () => {
          const res = await globalConfig.save({
            moduleCode: crudServiceVmTemplateConfig.tree.moduleCode,
            vmCode: submitVmCode,
            data: transFormData(formData.value, metaItemList.value),
            vmTemplateConfig: crudServiceVmTemplateConfig.tree,
          });
          if (isSuccessReqBackend(res)) {
            treeRef.value.append(getBackendData(res), null);
          }
        },
        buildInAddChildIntoCurBtn: async () => {
          console.log(crudServiceVmTemplateConfig.tree.moduleCode,submitVmCode,'打印提交数据')
          return;
          const res = await globalConfig.save({
            moduleCode: crudServiceVmTemplateConfig.tree.moduleCode,
            vmCode: submitVmCode,
            data: transFormData(formData.value, metaItemList.value),
            vmTemplateConfig: crudServiceVmTemplateConfig.tree,
          });
          if (isSuccessReqBackend(res)) {
            treeRef.value.append(getBackendData(res), formData.value[parentKeyField]);
          }
        },
        buildInEditBtn: async () => {
          const res = await globalConfig.update({
            moduleCode: crudServiceVmTemplateConfig.tree.moduleCode,
            vmCode: submitVmCode,
            data: transFormData(formData.value, metaItemList.value),
            vmTemplateConfig: crudServiceVmTemplateConfig.tree,
          });
        },
        buildInRowDeleteBtn: async () => {
          const res = await globalConfig.deleteBatch({
            moduleCode: crudServiceVmTemplateConfig.tree.moduleCode,
            vmCode: submitVmCode,
            params: {
              ids: [curFormData[keyField]],
            },
            vmTemplateConfig: crudServiceVmTemplateConfig.tree,
          });
          if (isSuccessReqBackend(res)) {
            treeRef.value.remove(curFormData);
          }
        },
      };
      await submitEventStrategy[submitEventstrategyName]();
    },
  };
  let isPassBeforeClick = true;
  try {
    beforeClickFunc({
      formData,
      callback,
    });
  } catch (e) {
    console.warn(e.message);
    isPassBeforeClick = false;
  }
  if (!isPassBeforeClick) {
    return;
  }

  const loadingInstance = !excludeLoadingStrategys.includes(eventstrategyName)
    ? gdLoadingService({ fullscreen: true })
    : false;

  const isOverrideBuildInContainerEmitEvent =
    crudServiceVmTemplateConfig.tree?.strategys?.hasOwnProperty(eventstrategyName);
  const isOverrideBuildInContainerSubmitBtn =
    crudServiceVmTemplateConfig.tree?.strategys?.[eventstrategyName]?.hasOwnProperty(submitEventstrategyName);
  let isOverrideStrategyExists = false;
  console.log(crudServiceVmTemplateConfig,'拦截时间策略=====')
  if (isOverrideBuildInContainerSubmitBtn) {
    let doExec = null;
    if (
      typeof crudServiceVmTemplateConfig.tree.strategys.buildInContainerSubmitBtn[submitEventstrategyName] ===
      "function"
    ) {
      doExec = crudServiceVmTemplateConfig.tree.strategys.buildInContainerSubmitBtn[submitEventstrategyName];
    } else if (
      typeof crudServiceVmTemplateConfig.tree.strategys.buildInContainerSubmitBtn[submitEventstrategyName] === "string"
    ) {
      doExec = new Function(
        "configObj",
        crudServiceVmTemplateConfig.tree.strategys.buildInContainerSubmitBtn[submitEventstrategyName]
      );
    }
    if (doExec) {
      isOverrideStrategyExists = true;
      await doExec(overrideEventFuncParams);
    }
  } else if (isOverrideBuildInContainerEmitEvent) {
    let doExec = null;
    if (typeof crudServiceVmTemplateConfig.tree.strategys[eventstrategyName] === "function") {
      doExec = crudServiceVmTemplateConfig.tree.strategys[eventstrategyName];
    } else if (typeof crudServiceVmTemplateConfig.tree.strategys[eventstrategyName] === "string") {
      doExec = new Function("configObj", crudServiceVmTemplateConfig.tree.strategys[eventstrategyName]);
    }
    if (doExec) {
      isOverrideStrategyExists = true;
      overrideEventFuncParams["orgMethod"] = events[eventstrategyName];
      await doExec(overrideEventFuncParams);
    }
  }
  if (
    (!isOverrideStrategyExists && events.hasOwnProperty(eventstrategyName)) ||
    (isOverrideStrategyExists && overrideEventFuncParams.isPassThrough)
  ) {
    await events[eventstrategyName]();
  } else {
  }
  loadingInstance && loadingInstance.close();

  isShowContainer.value =
    isOverrideStrategyExists && !overrideEventFuncParams.isPassThrough
      ? overrideEventFuncParams.willIsShowContainer
      : willIsShowContainer;
};

/**
 * tree相关事件策略调度
 */
export default (nodeKey, parentNodeKey, props) => {
  /**
   * 按钮事件 及其 弹窗相关
   */
  const isShowContainer = ref(false);
  const oldOperationEventParams = ref({});
  const containerAttr = ref({
    containerStyle: "Dialog",
  });

  ////////////
  let cacheContainerAttr = {};
  const setContainerAttr = (params) => {
    if (params.metaKey === "buildInContainerSubmitBtn") {
      containerAttr.value = cacheContainerAttr;
      return;
    }
    cacheContainerAttr = params?.metaItem?.containerAttr ?? {};
    containerAttr.value = cacheContainerAttr;
  };
  ///////////
  const formData = ref({});
  const metaItemList = ref([]);
  const containerEventFromConfig = reactive({
    rowIdx: null,
    rowData: null,
    formData: null,
  });
  ////////////////
  const crudServiceVmTemplateConfig = inject("crudServiceVmTemplateConfig", reactive({ tree: {} }));
  ///////////////
  const treeRef = ref(null);
  const myEmits = async (eventName, params) => {
    if (eventName === "do-operation") {
      ////////////
      if (!params.metaItem.hasOwnProperty("containerAttr")) {
        params.metaItem.containerAttr = {};
      }
      params.metaItem.containerAttr.appendToBody = params.metaItem.containerAttr?.appendToBody ?? true;
      ////////////
      setContainerAttr(params);
      ///////////
      await doEventstrategy({
        newOperationEventParams: params,
        oldOperationEventParams: oldOperationEventParams.value,
        nodeKey,
        parentNodeKey,
        isShowContainer,
        containerEventFromConfig,
        metaItemList,
        props,
        formData,
        crudServiceVmTemplateConfig,
        treeRef,
      });
      oldOperationEventParams.value = params;
    }
  };
  return {
    isShowContainer,
    formData,
    metaItemList,
    containerAttr,
    containerEventFromConfig,
    treeRef,
    myEmits,
    crudServiceVmTemplateConfig,
  };
};
